#include <unistd.h>
#include <stdlib.h>
#include <iostream>
#include "Screen.hh"
#include "utils.hh"
#include "slScene.hh"

#include <bullet/btBulletDynamicsCommon.h>

Screen::Screen(int width, int height) :
	glContext(0)
{
	_loop = true;
	_width = width;
	_height = height;
	framerate = 1000 / 60;

	if (SDL_Init(SDL_INIT_VIDEO) < 0)
	{
		std::cerr << "Error while inintialising SDL..." << std::endl;
		SDL_Quit();
		exit(-1);
	}

	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
    SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);

	window = SDL_CreateWindow("Bullet ftw", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL);

	glContext = SDL_GL_CreateContext(window);

	if (glContext == 0)
	{
		std::cerr << "Error while creating opengl context" << std::endl;
		SDL_DestroyWindow(window);
		SDL_Quit();
		exit(-1);
	}

	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluPerspective(70,(double)width/height,1,1000);
	glEnable(GL_DEPTH_TEST);
	glEnable(GL_TEXTURE_2D);
	glEnable(GL_NORMALIZE);
	glEnable(GL_LIGHTING);

	std::cout << "Glew init : [" << glewInit() << "]" << std::endl;
}

Screen::~Screen()
{
	SDL_GL_DeleteContext(glContext);
	SDL_DestroyWindow(window);
	SDL_Quit();
}

void    Screen::_drawBackground()
{

}

void		Screen::mainLoop()
{
	World 	world;
	slCamera camera(glm::vec3(3, 3, 3), glm::vec3(0, 0, 0), glm::vec3(0, 1, 0));
	input.showCursor(false);
	input.catchCursor(true);

	Uint32 time1 = 0, time2 = 0, elaspedTime = 0;

	slScene scene(&world, &input, &camera);

	while (_loop)
	{
		SDL_WarpMouseInWindow(window, 640, 360);
		time1 = SDL_GetTicks();
		input.updateInput();
		camera.move(input);

		if (input.isFinished() || input.getKey(SDL_SCANCODE_ESCAPE))
			_loop = false;

		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		glMatrixMode( GL_MODELVIEW );
		glLoadIdentity();

		camera.lookAt();
		scene.draw();


		glFlush();
        SDL_GL_SwapWindow(window);
		Uint32 time2 = SDL_GetTicks();
		elaspedTime = SDL_GetTicks() - time1;
		if (elaspedTime < framerate)
			SDL_Delay(framerate - elaspedTime);
	}
}